package com.wandousoushu.jiusen
import android.annotation.SuppressLint
import android.content.Intent
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.text.TextUtils
import android.webkit.WebView
import android.widget.Toast
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.wandousoushu.jiusen.base.BaseActivity
import com.wandousoushu.jiusen.bean.H5AdBean
import com.wandousoushu.jiusen.bean.UserInfo
import com.wandousoushu.jiusen.booksource.data.entities.Book
import com.wandousoushu.jiusen.booksource.model.BookManager
import com.wandousoushu.jiusen.booksource.model.BookSourceManager
import com.wandousoushu.jiusen.booksource.model.SearchBookManager
import com.wandousoushu.jiusen.ui.login.LoginActivity
import com.wandousoushu.jiusen.util.GsonUtils
import com.wandousoushu.jiusen.util.getPrefString
import com.wandousoushu.jiusen.util.putPrefString
import com.wandousoushu.jiusen.web.http.MainHttpConsts
import com.wandousoushu.jiusen.web.http.MainHttpUtils
import kotlinx.android.synthetic.main.activity_welcome.*
import org.jetbrains.anko.startActivity
import org.json.JSONArray
import org.json.JSONObject
open class WelcomeActivity : BaseActivity(R.layout.activity_welcome) {
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        // 避免从桌面启动程序后，会重新实例化入口类的activity
        if (intent.flags and Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT != 0) {
            finish()
        } else {
            init()
        }
    }
    private fun init() {
        root_view.postDelayed({ startMainActivity() }, 3000)
    }
    private fun startMainActivity() {
        val webView = WebView(applicationContext)
        HttpGetBookSource()
        val wxopenid=applicationContext.getPrefString("wxopenid")
        if(!wxopenid.isNullOrEmpty()){
            if (isWXAppInstalledAndSupported()) {  // 用户是否安装微信客户端
                // send oauth request
                HttpWxLogin()
            } else {
                Toast.makeText(this, "用户没有安装微信", Toast.LENGTH_SHORT).show()
                startActivity<LoginActivity>()
                finish()
            }
        }else{
            val phoneNum=applicationContext.getPrefString("account")
            val password=applicationContext.getPrefString("password")
            if (phoneNum.isNullOrEmpty()||password.isNullOrEmpty()){
                startActivity<LoginActivity>()
                finish()
            }else{
                HttpLogin()
            }
        }
        webView.destroy()
    }

    private fun isWXAppInstalledAndSupported(): Boolean {
        val msgApi = WXAPIFactory.createWXAPI(this, null)
        msgApi.registerApp(MainHttpConsts.WX_APP_ID)
        return (msgApi.isWXAppInstalled)
    }

    private fun HttpLogin() {
        Thread(Runnable {
            try {
                val phoneNum=applicationContext.getPrefString("account")
                val returnData = MainHttpUtils.getInstance().Login(phoneNum, applicationContext.getPrefString("password"))
                if (returnData == null) {
                    return@Runnable
                }
                val jsonObject = JSONObject(returnData)
                if (jsonObject.getInt("code") == 1) {
                    val data = jsonObject.getString("data")
                    if (!TextUtils.isEmpty(data)) {
                        val userInfo = GsonUtils.parseJObject(data, UserInfo::class.java)
                        if (userInfo != null) {
                            MyApplication.instance.token = userInfo.token
                            MyApplication.instance.nickName = userInfo.user_nickname
                            MyApplication.instance.phoneNum = phoneNum
                            MyApplication.instance.userId = userInfo.id
                            MyApplication.instance.isVip = if (userInfo.is_vip == 1) true else false
                            MyApplication.instance.userinfo = userInfo
                            MyApplication.instance.isLogin=true
                        }
                    } else {
                        return@Runnable
                    }
                    mHandle.sendEmptyMessage(1)
                } else {
                    val msg = Message.obtain()
                    msg.obj = jsonObject.getString("msg")
                    msg.what = 2
                    mHandle.sendMessage(msg)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }).start()
    }

    private fun HttpWxLogin() {
        Thread(Runnable {
            try {
                val wxopenid=applicationContext.getPrefString("wxopenid")
                val returnData = MainHttpUtils.getInstance().WeiXinLogin(wxopenid,"","")
                if (returnData == null) {
                    return@Runnable
                }
                val jsonObject = JSONObject(returnData)
                if (jsonObject.getInt("code") == 1) {
                    val data = jsonObject.getString("data")
                    if (!TextUtils.isEmpty(data)) {
                        val userInfo = GsonUtils.parseJObject(data, UserInfo::class.java)
                        if (userInfo != null) {
                            MyApplication.instance.token = userInfo.token
                            MyApplication.instance.nickName = userInfo.user_nickname
                            MyApplication.instance.phoneNum = "微信用户"
                            MyApplication.instance.userId = userInfo.id
                            MyApplication.instance.isVip = if (userInfo.is_vip == 1) true else false
                            MyApplication.instance.userinfo = userInfo
                            MyApplication.instance.isLogin=true
                            MyApplication.instance.isWxUser=true
                            applicationContext.putPrefString("wxopenid",userInfo.openid)
                        }
                    } else {
                        return@Runnable
                    }
                    mHandle.sendEmptyMessage(1)
                } else {
                    val msg = Message.obtain()
                    msg.obj = jsonObject.getString("msg")
                    msg.what = 2
                    mHandle.sendMessage(msg)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }).start()
    }

    private fun HttpGetBookSource() {
        Thread(Runnable {
            try {
                val returnData = MainHttpUtils.getInstance().GetBookSource()
                if (returnData == null) {
                    return@Runnable
                }
                val jsonObject = JSONObject(returnData)
                if (jsonObject.getInt("code") == 1) {
                    val data = jsonObject.getString("data")
                    if (TextUtils.isEmpty(data)) return@Runnable
                    val bookSourceList = BookSourceManager.GetInstance().importBookSourceFromJson(data)
                    if (bookSourceList.size == 0) {
                        mHandle.sendEmptyMessage(3)
                        return@Runnable
                    } else {
                        BookSourceManager.GetInstance().AddBookSources(bookSourceList)
                        //MyApplication.instance.AddBookSources(bookSourceList)
                    }
                } else {
                    val msg = Message.obtain()
                    msg.obj = jsonObject.getString("msg")
                    msg.what = 2
                    mHandle.sendMessage(msg)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }).start()
    }

    private fun HttpGetSearckKey() {
        Thread(Runnable {
            try {
                val returnData = MainHttpUtils.getInstance().GetSearchKeys(MyApplication.instance.token)
                        ?: return@Runnable
                val jsonObject = JSONObject(returnData)
                if (jsonObject.getInt("code") == 1) {
                    val data = jsonObject.getString("data")
                    if (TextUtils.isEmpty(data)) {
                        return@Runnable
                    }
                    val historyKeys = GsonUtils.parseJArray(data, String::class.java)
                    SearchBookManager.GetInstance().AddHistoryKeys(historyKeys)
                } else {
                    val msg = Message.obtain()
                    msg.obj = jsonObject.getString("msg")
                    msg.what = 2
                    mHandle.sendMessage(msg)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }).start()
    }

    private fun HttpGetBookMark() {
        Thread(Runnable {
            try {
                val returnData = MainHttpUtils.getInstance().GetBooks(1, MyApplication.instance.token) ?: return@Runnable
                val jsonObject = JSONObject(returnData)
                if (jsonObject.getInt("code") == 1) {
                    val data = jsonObject.getString("data")
                    if (TextUtils.isEmpty(data)) return@Runnable
                    val jObject = JSONObject(data)
                    val lists = jObject.getString("lists")
                    val jsonArray = JSONArray(lists)
                    for (i in 0 until jsonArray.length()) {
                        val json = jsonArray[i] as JSONObject
                        val book = Book()
                        book.name = json.getString("name")
                        book.bookUrl = json.getString("url")
                        book.tocUrl = json.getString("chapter_url")
                        book.latestChapterTitle = json.getString("final_refresh_data")
                        book.coverUrl = json.getString("cover_url")
                        book.author = json.getString("author")
                        book.intro = json.getString("introduce")
                        book.origin = json.getString("origin")
                        book.originName = json.getString("origin_name")
                        book.charset = json.getString("charset")
                        book.group = 1
                        book.durChapterTitle = json.getString("dur_chapter_title")
                        book.durChapterIndex = json.getInt("dur_chapter_index")
                        book.durChapterPos = json.getInt("dur_chapter_pos")
                        book.order=i
                        BookManager.GetInstance().AddBook(book)
                    }
                } else {
                    val msg = Message.obtain()
                    msg.obj = jsonObject.getString("msg")
                    msg.what = 2
                    mHandle.sendMessage(msg)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }).start()
    }

    private fun HttpGetPageAd() {
        Thread(Runnable {
            try {
                val returnData = MainHttpUtils.getInstance().GetPageViewAdH5()
                if (returnData == null) {
                    return@Runnable
                }
                val jsonObject = JSONObject(returnData)
                if (jsonObject.getInt("code") == 1) {
                    val data = jsonObject.getString("data")
                    if (TextUtils.isEmpty(data)) return@Runnable
                    MyApplication.instance.pageH5=GsonUtils.parseJObject(jsonObject.getString("data"), H5AdBean::class.java)
                    //MyApplication.instance.pageAdList = GsonUtils.parseJArray(jsonObject.getString("data"), AdBean::class.java)
                } else {
                    val msg = Message.obtain()
                    msg.obj = jsonObject.getString("msg")
                    msg.what = 2
                    mHandle.sendMessage(msg)
                }
            } catch (e: Exception) {
                e.printStackTrace()
            }
        }).start()
    }

    private val mHandle: Handler = @SuppressLint("HandlerLeak")
    object : Handler() {
        @SuppressLint("HandlerLeak")
        override fun handleMessage(msg: Message) {
            when (msg.what) {
                0 -> {
                    Toast.makeText(applicationContext, resources.getString(R.string.login_http_fail), Toast.LENGTH_SHORT).show()
                    val intent = Intent(applicationContext, LoginActivity::class.java)
                    startActivity(intent)
                    finish()
                }
                1 -> {
                    //Toast.makeText(applicationContext, resources.getString(R.string.login_auth_success), Toast.LENGTH_SHORT).show()
                    //HttpGetBookSource()
                    HttpGetSearckKey()
                    HttpGetBookMark()
                    HttpGetPageAd()
                    val intent = Intent(applicationContext, MainActivity::class.java)
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_NEW_TASK)
                    startActivity(intent)
                }
                2 -> Toast.makeText(applicationContext, msg.obj.toString(), Toast.LENGTH_SHORT).show()
                3 -> Toast.makeText(applicationContext, resources.getString(R.string.booksource_http_fail), Toast.LENGTH_SHORT).show()

            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
    }
}
class Launcher1 : WelcomeActivity()
class Launcher2 : WelcomeActivity()
class Launcher3 : WelcomeActivity()
class Launcher4 : WelcomeActivity()
class Launcher5 : WelcomeActivity()
class Launcher6 : WelcomeActivity()